package com.laex;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;

public class CategoryManager extends Form {

	private Command addCategoryCMD;
	private TextField categoryTXT;

	public CategoryManager(Command back) {
		super("Category Manager");

		addCategoryCMD = new Command("Add", Command.ITEM, 1);
		categoryTXT = new TextField(null, "", 100, TextField.ANY);
		
		this.append(categoryTXT);
		this.addCommand(addCategoryCMD);
		this.addCommand(back);
		
		displayCategories();
	}

	public void displayCategories() {
		String[] sarr = RecordUtil.getCategories();
		listUpCategories(sarr);
	}

	private void listUpCategories(String[] sarr) {
		for (int i = 0; i < sarr.length; i++) {
			if (sarr[i] != null) {
				this.append(POEUtil.getExpenseReportIcon());
				this.append(new StringItem("", sarr[i] + "\n"));
			}
		}
	}
	
	public void addCategory() {
		String cat = categoryTXT.getString();
		if (cat.trim().length() != 0) {
			RecordUtil.insertCategory(cat);
			categoryTXT.setString("");
			String[] sarr = RecordUtil.getCategories();
			removeCategoriesFromScreen(sarr);
			listUpCategories(sarr);
		}
	}

	private void removeCategoriesFromScreen(String[] sarr) {
		for (int i=this.size() -1 ; i >= 1; i--) {
			this.delete(i);
		}
	}
	
	public Command getAddCommand() {
		return addCategoryCMD;
	}
}
